package org.wii.base.utils;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

/**
 * Spring Bean Util
 * @author tanghong on 2022/12/22
 */
@Slf4j
@Component
public class SpringBeanUtil implements ApplicationContextAware, DisposableBean {
    private static ApplicationContext applicationContext;

    @Override
    public void destroy() throws Exception {
        SpringBeanUtil.applicationContext =  null;
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        SpringBeanUtil.applicationContext = applicationContext;
    }

    public static <T> T getBean(Class<T> clazz){
        if (null == applicationContext){
            throw new RuntimeException("上下文初始化未完成!");
        }
        return applicationContext.getBean(clazz);
    }
}
